import axios from 'axios';
import qs from 'qs';
import { newDecrypt } from './userAes';

const localUrl = 'https://cmtest.qrcode.sh.gov.cn:443/jmportal_xcx'; //测试
const grayUrl = 'http://183.194.244.12/jmportal_test'; //灰度
const baseUrl = 'https://ywtbsupappz.sh.gov.cn/jmportal_hd'; //正式

const instance = axios.create({
  // localUrl, //baseURL会在发起请求的时候自动拼接在url前面
  timeout: 500000,
});

instance.interceptors.response.use(
  //响应拦截
  function (res) {
    return res;
  },
  function (err) {
    // console.log('ss')
    let { response } = err;
    if (response) {
      // 服务器返回结果
      switch (response.status) {
        //判断错误编码
        case 401:
          break;
        case 403:
          break;
        case 404: //
          break;
      }
    } else {
      // console.log('ss')
      // 服务器崩溃或者断网
      if (!window.navigator.onLine) {
        // 断网处理  可以跳转到断网页面
        return;
      }
    }
    return Promise.reject(err);
  }
);

class HTTP {
  static async post(url: string, jsonParam: object) {
    console.log(jsonParam);
    let data = qs.stringify(jsonParam);
    // console.log(data);
    return new Promise((resolve, reject) => {
      instance
        .post(url, data, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
          },
        })
        .then((res) => {
          let key = atob(res.headers['serial-number']);
          let result = newDecrypt(res.data.result, key);
          resolve(JSON.parse(result));
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
}

export { HTTP, localUrl, baseUrl, grayUrl };
